package com.qst.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 邮箱验证工具类
 */
public class EmailValidator {

    private static final Logger logger = LoggerFactory.getLogger(EmailValidator.class);

    // 常见的有效邮箱域名
    private static final Set<String> VALID_EMAIL_DOMAINS = new HashSet<>(Arrays.asList(
            "qq.com", "163.com", "126.com", "sina.com", "sina.cn", "sohu.com",
            "gmail.com", "outlook.com", "hotmail.com", "yahoo.com", "foxmail.com",
            "139.com", "189.cn", "yeah.net", "vip.qq.com", "vip.sina.com"
    ));

    // 邮箱格式正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
    );

    /**
     * 验证邮箱格式
     */
    public static boolean isValidFormat(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        return EMAIL_PATTERN.matcher(email.trim()).matches();
    }

    /**
     * 验证邮箱域名是否在白名单中
     */
    public static boolean isValidDomain(String email) {
        if (!isValidFormat(email)) {
            return false;
        }

        String domain = email.substring(email.indexOf('@') + 1).toLowerCase();
        boolean isValid = VALID_EMAIL_DOMAINS.contains(domain);
        
        if (!isValid) {
            logger.warn("邮箱域名不在白名单中: {}", domain);
        }
        
        return isValid;
    }

    /**
     * 验证邮箱（格式 + 域名）
     */
    public static boolean validate(String email) {
        return isValidFormat(email) && isValidDomain(email);
    }

    /**
     * 获取邮箱域名
     */
    public static String getDomain(String email) {
        if (email == null || !email.contains("@")) {
            return null;
        }
        return email.substring(email.indexOf('@') + 1).toLowerCase();
    }
}

